package com.eova.common.base;

import java.util.HashSet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eova.common.utils.xx;
import com.eova.config.EovaConst;
import com.eova.model.User;
import com.jfinal.core.Controller;
import com.jfinal.json.Json;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Ret;

public class BaseController extends Controller {

	public String http(String domain) {
		return "http://" + xx.getConfig(domain);
	}

	public int UID() {
		return getUser().getInt("id");
	}

	public User getUser() {
		return (User) getSessionAttr(EovaConst.USER);
	}

	/**
	 * <pre>
	 * 获取选中行某列的值
	 * 多选且为整型:1,2,3
	 * 多选且为字符:'a','b','c' 
	 * PS:多选的处理方便取值后直接in
	 * </pre>
	 * @param field 字段名
	 */
	public String getSelectValue(String field) {
		// 单选
		JSONArray rows = getSelectRows();
		if (rows.isEmpty()) {
			return null;
		}
		if (rows.size() == 1) {
			return rows.getJSONObject(0).getString(field);
		}

		boolean isNum = true;
		// 多选
		HashSet<String> set = new HashSet<>();
		for (int i = 0; i < rows.size(); i++) {
			Object val = rows.getJSONObject(i).get(field);
			set.add(val.toString());
			if (!xx.isNum(val))
				isNum = false;
		}
		if (isNum) {
			return xx.join(set);
		} else {
			return xx.join(set, "'", ",");
		}
	}

	/**
	 * 获取所有选中行
	 * 
	 * @return
	 */
	public JSONArray getSelectRows() {
		String json = getPara("rows");
		JSONArray o = JSONObject.parseArray(json);
		return o;
	}

	/**
	 * 获取按钮输入框的值
	 * <pre>
	 * Integer id = getSelectValue("id");
	 * 
	 * if (xx.isEmpty(val)) {
	 *     renderJson(new Easy("参数不能为空！"));
	 *     return;
	 * }
	 * 
	 * Db.update("update xxx set xx = ? where id = ?", val, id);
	 * renderJson(Easy.sucess());
	 *</pre>
	 */
	public String getInputValue() {
		return getPara("input");
	}

	/**
	 * 获取JSONObject
	 * 
	 */
	public Ret getJsonToRet() {
		String s = HttpKit.readData(getRequest());
		if (xx.isEmpty(s)) {
			return null;
		}
		return Json.getJson().parse(s, Ret.class);
		// return JSONObject.parseObject(HttpKit.readData(getRequest()));
	}

}